package zhihui.mobile.presenter.main;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zgm.utils.DateUtils;
import com.zgm.utils.FileUtils;
import com.zgm.utils.PermissionsChecker;
import com.zgm.utils.ZipUtil;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;

import de.mindpipe.android.logging.log4j.LogConfigurator;
import zhihui.mobile.R;
import zhihui.mobile.app.CrashHandler;
import zhihui.mobile.bean.message.MessageInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.interfaces.net.IHttpCallBackListener;
import zhihui.mobile.manager.MessageManager;
import zhihui.mobile.presenter.shop.BaseShopPresenter;
import zhihui.mobile.ui.IView;
import zhihui.mobile.ui.utils.SharedPreferenceUtils;
import zhihui.mobile.ui.utils.UiUtils;

/**
 * Created by 张公铭 on 2017/7/3 0003.
 */

public class MainPresenter extends BaseShopPresenter implements IMainContract.IMainPresenter
{
    private IMainContract.IMainView mainView;
    private Context mContext;
    private LogConfigurator logConfigurator;

    //需要的权限
    private final String[] PERMISSIONS = new String[]{
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.READ_PHONE_STATE",
            "android.permission.CAMERA",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION"
    };

    @Override
    public void init(IView view, Context context)
    {
        mainView = (IMainContract.IMainView) view;
        mContext = context;
        //initConf();
    }

    @Override
    public void onResume()
    {
        if (!Config.isInit)
        {
            PermissionsChecker permissionsChecker = new PermissionsChecker(mContext);
            if (permissionsChecker.lacksPermissions(PERMISSIONS))
            {
                mainView.requestPermissions(PERMISSIONS);
            } else
            {
                initCrahAndLog();
            }
        }

        if (UiUtils.check(mContext))
        {
            refreshMessage();
        }

    }

    /**
     * 初始化资源文件
     */
    private void initConf()
    {
        boolean isInit = SharedPreferenceUtils.getConState(mContext);
        if (isInit)
        {
            new ResConfTask().execute();
        }
    }

    //解压资源
    class ResConfTask extends AsyncTask<Void, Void, Boolean>
    {
        @Override
        protected void onPreExecute()
        {
            mainView.showLoading();
        }

        @Override
        protected Boolean doInBackground(Void... params)
        {
            try
            {
                ZipUtil.unZip(mContext, Config.confZip, FileUtils.getDir() + Config.conf, true);
            } catch (IOException e)
            {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean)
        {
            mainView.hindLoading();
            if (!aBoolean)
            {
                mainView.showMessage("解压资源文件失败！");
            } else
            {
                SharedPreferenceUtils.setConSatet(mContext, false);
            }
        }
    }

    @Override
    public void onStart()
    {

    }

    @Override
    public void onPause()
    {

    }

    @Override
    public void onStop()
    {

    }

    @Override
    public void onDestroy()
    {

    }

    /**
     * 初始化日志
     */
    private void initLog()
    {
        if (Config.PULISH_VERSION == 0)
        {
            Config.initLogLevel();
        }

        logConfigurator = new LogConfigurator();
        String path = FileUtils.getDir().getPath() + Config.logDir + File.separator + "zhihuiMM_"
                + DateUtils.getCurrentTime().toString().replace(" ", "_").replace(":", "_") + ".log";

        File file = new File(path);
        if (!file.exists())
        {
            File parentDir = file.getParentFile();
            Log.e("xxxx", parentDir.getPath());
            if (!parentDir.exists())
            {
                boolean successs = parentDir.mkdirs();
                Log.e("xxx", "success:" + successs);
            }
            try
            {
                file.createNewFile();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        logConfigurator.setFileName(file.getAbsolutePath());
        logConfigurator.setRootLevel(Config.log_level);
        logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
        logConfigurator.setMaxFileSize(1024 * 1024 * 5);
        logConfigurator.setImmediateFlush(true);
        logConfigurator.configure();
    }

    @Override
    public void initCrahAndLog()
    {
        ///初始化Crash
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(mContext.getApplicationContext(), FileUtils.getDir().getPath() + Config.crashDir);

        initLog();
    }

    @Override
    public void refreshMessage()
    {
        mainView.showLoading();
        MessageManager.getInstance().getMessageList(new IHttpCallBackListener()
        {
            @Override
            public void success(JSONObject result)
            {
                mainView.hindLoading();
                Gson gson = new Gson();
                try
                {
                    List<MessageInfo> list = gson.fromJson(result.getJSONArray("data").toString(), new TypeToken<List<MessageInfo>>(){}.getType());
                    mainView.refreshMessage(list);
                    mainView.onRefreshComplete();
                } catch (JSONException e)
                {
                    e.printStackTrace();
                    mainView.showMessage(mContext.getString(R.string.json_error));
                    mainView.onRefreshComplete();
                }
            }

            @Override
            public void failed(String message)
            {
                mainView.hindLoading();
                mainView.showMessage(message);
                mainView.onRefreshComplete();
            }
        }, 10);
    }
//    @Override
//    public void addShopInCard()
//    {
//        ShopAddressManager.getInstance().getUserAddress(new IHttpCallBackListener()
//        {
//            @Override
//            public void success(JSONObject result)
//            {
//
//            }
//
//            @Override
//            public void failed(String message)
//            {
//
//            }
//        });
//    }

//    //获取订单列表
//    private void getShopOrderes()
//    {
//        mainView.showLoading();
//        ShopOrderManager.getInstance().getShopOrders(new IHttpCallBackListener()
//        {
//            @Override
//            public void success(JSONObject result)
//            {
//                mainView.hindLoading();
//                try
//                {
//                    JSONObject data = result.getJSONObject("data");
//                    int timeover = data.getInt("timeover");
//                    ShopOrderManager.getInstance().timeover = timeover;
//                    List<ShopOrder> list = new ArrayList<>();
//                    Gson gson = new Gson();
//                    list = gson.fromJson(data.getJSONArray("list").toString(), new TypeToken<List<ShopOrder>>()
//                    {
//                    }.getType());
//                    ShopOrderManager.getInstance().setOrderList(list);
//                    mainView.goTest();
//                } catch (JSONException e)
//                {
//                    e.printStackTrace();
//                    mainView.showMessage(mContext.getString(R.string.json_error));
//                }
//            }
//
//            @Override
//            public void failed(String message)
//            {
//                mainView.hindLoading();
//                mainView.showMessage(message);
//            }
//        });
//    }
//
//
//    @Override
//    public void getAddresss()
//    {
//        mainView.showLoading();
//        ShopAddressManager.getInstance().getUserAddress(new IHttpCallBackListener()
//        {
//            @Override
//            public void success(JSONObject result)
//            {
//                mainView.hindLoading();
//                Gson gson = new Gson();
//                try
//                {
//                    List<ShoppingAddress> list = gson.fromJson(result.getJSONArray("data").toString(), new TypeToken<List<ShoppingAddress>>()
//                    {
//                    }.getType());
//                    ShopAddressManager.getInstance().setmList(list);
//                    mainView.goShopAddressMangerAcvity();
//                } catch (JSONException e)
//                {
//                    mainView.showMessage(mContext.getString(R.string.json_error));
//                }
//            }
//
//            @Override
//            public void failed(String message)
//            {
//                mainView.hindLoading();
//                mainView.showMessage(message);
//            }
//        });
//    }
//
//    @Override
//    public void test()
//    {
//        getShopOrderes();
//    }
}
